package com.eastfair.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.base.BaseControllerInfo;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.tenant.TenantAuth;
import com.eastfair.auth.dao.BusinessMapper;
import com.eastfair.auth.dto.*;
import com.eastfair.auth.entity.Organization;
import com.eastfair.auth.entity.Role;
import com.eastfair.auth.enumeration.OrganizationVestTypeEnum;
import com.eastfair.auth.enumeration.RoleRoleTypeEnum;
import com.eastfair.auth.service.OrganizationService;
import com.eastfair.auth.service.RoleService;
import com.eastfair.auth.service.UserAccountService;
import com.eastfair.auth.vo.OrganizationVo;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.demand.auth.OrganizationVoGroupClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.eastfair.core.base.R.SUCCESS_CODE;


/**
 * <p>
 * 全局业务控制器
 *
 * </p>
 *
 * @author ligang
 * @date 2021-07-23
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/global")
@Api(value = "global", tags = "全局数据业务接口")
public class GlobalBusinessController {

    @Autowired
    UserAccountService userAccountService;

    @Autowired
    BusinessMapper businessMapper;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    RoleService roleService;

    /**
     * 查询子系统大角色
     *
     * @param params 参数
     */
    @ApiOperation(value = "查询子系统大角色")
    @PostMapping(value = "/querySubsystemRole")
    @TenantAuth(enabled = true)
    public R<Page<Role>> querySubsystemRole(@RequestBody PageParams<RoleDTO> params) {
        RoleDTO roleDTO = params.getModel();
        //查询
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (roleDTO != null) {
            if (StringUtils.isNotBlank(roleDTO.getName())) {
                queryWrapper.lambda().eq(Role::getName, roleDTO.getName());
            }
        }
        queryWrapper.lambda().ne(Role::getRoleType, RoleRoleTypeEnum.OTHER);
        queryWrapper.lambda().eq(Role::getProjectId, ContextUtil.getProjectId());
        queryWrapper.lambda().eq(Role::getIsDeleted, BusinessConstant.DELETE_NO);

        Page<Role> page = new Page<>(params.getCurrent(), params.getSize());
//        roleService.list(queryWrapper);
        page = roleService.page(page, queryWrapper);

//        IPage<UserAccountVo> userAccountVoIPage = businessMapper.queryUser(servePage, queryWrapper);
        return R.success(page);
    }

    /**
     * 修改子系统大角色
     *
     * @param roleDTO 角色新增实体
     * @return
     */
    @ApiOperation(value = "修改子系统大角色", notes = "修改子系统大角色")
    @PutMapping("/udpateSystemRole")
    @TenantAuth(enabled = true)
    public R udpateSystemRole(@RequestBody @Validated({RoleDTO.udpateSystemRole.class}) RoleDTO roleDTO) {
        roleService.reloadRoleRelationOfMenu(roleDTO);
        //重新更新子团队根角色的菜单关系
        roleDTO.setSourceRoleId(roleDTO.getId());
        roleService.reloadRoleRelationOfSubSystem(roleDTO);
        return R.success();
    }

    /**
     * 查询全部子节点大组织
     *
     * @param organizationDTO 组织id
     * @return
     */
    @ApiOperation(value = "查询全部子节点大组织", notes = "查询全部子节点大组织")
    @PostMapping("/findAllParentOrgOfRoot")
    @SysLog("查询全部子节点大组织")
    @TenantAuth(enabled = true)
//    public R<Page<OrganizationVo>> findAllParentOrgOfRoot(@RequestBody PageParams<OrganizationDTO> params) {
    public R<List<OrganizationVo>> findAllParentOrgOfRoot(@RequestBody OrganizationDTO organizationDTO) {
//        OrganizationDTO organizationDTO = params.getModel();
//        Organization organization = new Organization();
//        BeanUtils.copyProperties(organizationDTO, organization);
//        organization.setParentId(BusinessConstant.parentId);
//        List<Organization> organizationList = organizationService.listOfOrganization(organization, null);
//        if (organizationList == null || organizationList.isEmpty()) {
//            return R.success(null);
//        }
        //查询
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        if (organizationDTO != null) {
            if (StringUtils.isNotBlank(organizationDTO.getName())) {
                queryWrapper.lambda().eq(Organization::getName, organizationDTO.getName());
            }

            if (organizationDTO.getOrgType() != null) {
                queryWrapper.lambda().eq(Organization::getOrgType, organizationDTO.getOrgType());
            }
        }
        queryWrapper.lambda().eq(Organization::getParentId, BusinessConstant.parentId);
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        queryWrapper.lambda().eq(Organization::getVestType, OrganizationVestTypeEnum.P);
        //排序查询
        queryWrapper.orderByAsc("sequence");
//        Page<Organization> page = new Page<>(params.getCurrent(), params.getSize());
//        page = organizationService.page(page, queryWrapper);
//        List<Organization> organizationList = organizationService.list(queryWrapper);
//        List<OrganizationVo> organizationVoList = organizationService.queryOrgNoResource(page.getRecords());
//        Page<OrganizationVo> msgTemplateVOPage = new Page<>();
//        BeanUtils.copyProperties(page, msgTemplateVOPage);

        List<Organization> organizationList = organizationService.list(queryWrapper);
        List<OrganizationVo> organizationVoList = organizationService.queryOrgNoResource(organizationList);
        List<OrganizationVo> resultOrganizationVoList = new ArrayList<>();
        for (OrganizationVo organizationVo : organizationVoList) {
            resultOrganizationVoList.add(organizationService.findAllByIdNoResource(organizationVo.getId()));
        }
//        msgTemplateVOPage.setRecords(resultOrganizationVoList);
//        Page<OrganizationVo> msgTemplateVOPage = ConvertUtil.convertPage(page, OrganizationVo.class);
        return R.success(resultOrganizationVoList);
    }


    /**
     * 查询角色和旗下菜单信息
     *
     * @param roleId 角色id
     * @return
     */
    @ApiOperation(value = "查询角色和旗下菜单信息", notes = "查询角色和旗下菜单信息")
    @GetMapping("/getRoleById/{roleId}")
    @TenantAuth(enabled = true)
    public R<RoleVo> getById(@PathVariable("roleId") Long roleId) {
        return R.success(roleService.getAllById(roleId));
    }


    /**
     * 创建节点组     * @return
     *
     * @param organizationDTO 组织实体
     */
    @ApiOperation(value = "创建节点组", notes = "创建节点组")
    @PostMapping("/createOrgGroup")
    @TenantAuth(enabled = true)
    public R createOrgGroup(@RequestBody @Validated({OrganizationDTO.VerifyGlobalCreateOrgGroup.class}) OrganizationDTO organizationDTO) {
        //指定子系统id
        ContextUtil.setSubSystemId(organizationDTO.getSubsystemId());
        return organizationService.createOrg(organizationDTO);
    }


    /**
     * 修改节点(前端用)
     *
     * @param organizationDTO 修改节点
     * @return
     */
    @ApiOperation(value = "修改节点", notes = "修改节点")
    @PutMapping("/updOrgGroupToLead")
    @TenantAuth(enabled = true)
    public R updOrgGroupToLead(@RequestBody @Validated({OrganizationDTO.VerifyGlobalUpdOrgGroup.class}) OrganizationDTO organizationDTO) {
        //指定子系统id
        ContextUtil.setSubSystemId(organizationDTO.getSubsystemId());
        return organizationService.updOrg(organizationDTO);
    }


    /**
     * 删除(前端用)
     *
     * @param ids 组织实体DTO
     * @return
     */
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/delToLead")
    @TenantAuth(enabled = true)
    public R delToLead(@RequestBody List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            for (Long id : ids) {
                organizationService.del(id);
            }
        }
        return R.success();
    }


    /**
     * 查询详情
     *
     * @param id 组织id
     * @return
     */
    @ApiOperation(value = "查询详情", notes = "查询详情")
    @GetMapping("/queryById/{id}")
    @TenantAuth(enabled = true)
//    @BaseControllerInfo(voGroup = {VoGroupClass.findAllOrganization.class})
    public R<OrganizationVo> queryById(@PathVariable("id") Long id) {
        return R.success(organizationService.findAllById(id));
    }


    /**
     * 通过类型查询所在的组织（集合，前端用），并查询旗下所有子节点
     *
     * @param organizationDTO 组织id
     * @return
     */
    @ApiOperation(value = "通过类型查询所在的组织（集合，前端用）", notes = "通过类型查询所在的组织（集合，前端用）")
    @PostMapping("/findAllOrgOfTypeToLead")
    @BaseControllerInfo(voGroup = {OrganizationVoGroupClass.findAllOrganization.class})
    @SysLog("通过资源查询所在的组织")
    @TenantAuth(enabled = true)
    public R<List<OrganizationVo>> findAllOrgOfTypeToLead(@RequestBody @Validated({OrganizationDTO.findAllOrgOfTypeToLead.class}) OrganizationDTO organizationDTO) {
        //指定子系统id
        ContextUtil.setSubSystemId(organizationDTO.getSubsystemId());
        Organization organization = organizationService.queryOrgOfType(organizationDTO.getOrgType(), organizationDTO.getParentId());
        if (organization != null) {
            OrganizationVo organizationVo = organizationService.findAllByIdNoResource(organization.getId());
            return R.success(Arrays.asList(organizationVo));
        }
        return R.success(null);
    }


    /**
     * 查询角色
     *
     * @return 查询结果
     */
    @ApiOperation(value = "查询角色", notes = "查询角色")
    @PostMapping("/queryRole")
    @TenantAuth(enabled = true)
    public R<List<RoleVo>> queryRole(@RequestBody RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        List<Role> roleList = roleService.list(role, null, null);
        List<RoleVo> roleVoList =  roleService.doToVos(roleList);
        if (roleList == null || roleList.isEmpty()) {
            return R.success(null);
        }
        for (RoleVo roleVo : roleVoList) {
            //查询菜单集合
            List<Long> menuIds = roleService.findMenuIdById(roleVo.getId());
            roleVo.setMenuIds(menuIds);
        }
        return R.success(roleVoList);
    }


}
